import os
from flask import Flask, render_template
import logging
import setting

from server.module.fileManager.files import fields
from server.module.textChat.textStore import TextStore
from server.module.textChat.textchat import chat
from server.utils.ssl.init import ssl_init

# ##### Application ##### #
app = Flask(
    __name__,
    template_folder=setting.html_path,
    static_folder=setting.html_path,
    static_url_path=''
)

# #### Application Setting ##### #
app.url_map.strict_slashes = False
log = logging.getLogger('werkzeug')
log.disabled = not setting.debug  # 在用命令行控制程序时(生产模式)，输出log会导致程序崩溃

# ##### Blueprint Registration ##### #
app.register_blueprint(fields)
app.register_blueprint(chat)


# ##### Application initiation ##### #
def StartServer():
    if not os.path.exists(setting.FilePath):
        os.mkdir(setting.FilePath)
    if not os.path.exists(setting.UploadPath):
        os.mkdir(setting.UploadPath)
    if not os.path.exists(setting.DownloadPath):
        os.mkdir(setting.DownloadPath)
    textStore = TextStore()
    if setting.protocol == 'https':
        ssl_init()
        # app.run(host=setting.host, port=setting.port, ssl_context='adhoc')
        app.run(
            host=setting.host, port=setting.port, debug=setting.debug,
            ssl_context=(setting.ssl_cert, setting.ssl_privateKey)
        )
    else:
        app.run(host=setting.host, port=setting.port, debug=setting.debug)


@app.route('/', methods=['get'])
def helloworld():
    return render_template(
        'index.html',
        login_required=str(bool(setting.simple_password)).lower(),
    )


if __name__ == "__main__":
    StartServer()
